package com.swz.dcrm.ui.car;


import android.os.Bundle;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;

import android.view.Gravity;
import android.view.View;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.swz.dcrm.adpter.CarBrandAdapter;
import com.swz.dcrm.adpter.CarSeriesAdapter;
import com.swz.dcrm.adpter.GlobalAdapter;
import com.swz.dcrm.model.BaseResponse;
import com.swz.dcrm.model.CarBrand;
import com.swz.dcrm.model.CarSeries;
import com.swz.dcrm.model.Page;
import com.swz.dcrm.model.PageResponse;
import com.swz.dcrm.ui.base.BaseFragment;
import com.swz.dcrm.R;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.OnClick;
import in.myinnos.alphabetsindexfastscrollrecycler.IndexFastScrollRecyclerView;

import com.swz.dcrm.ui.viewmodel.CarBrandViewModel;
import com.swz.dcrm.util.Tool;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.xh.baselibrary.callback.OnClickListener;

import java.util.List;

import javax.inject.Inject;

/**
 * A simple {@link Fragment} subclass.
 */
public class CarBrandFragment extends BaseFragment {

    @BindView(R.id.toolbar_title)
    TextView title;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.rv)
    IndexFastScrollRecyclerView rvCarBrand;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.drawer_container)
    LinearLayout container;
    @BindView(R.id.rv_car_series)
    RecyclerView rvCarSeries;
    @BindView(R.id.iv_brand_logo)
    ImageView ivBrandLogo;
    @BindView(R.id.tv_brand_name)
    TextView tvBrandName;

    @Inject
    CarBrandViewModel carBrandViewModel;

    private CarBrandAdapter carBrandAdapter;
    private CarSeriesAdapter carSeriesAdapter;

    public static CarBrandFragment newInstance() {

        return new CarBrandFragment();
        // Required empty public constructor
    }

    @Override
    public void onLoadRetry() {
        if (!isNetworkConnected(getContext())){
            mHolder.showLoadingStatus(GlobalAdapter.NET_ERROR);
            return;
        }
        CarBrandFragmentArgs carBrandFragmentArgs=CarBrandFragmentArgs.fromBundle(getArguments());
        if(!carBrandFragmentArgs.getBrand().equals("test")){

            CarBrand carBrand=new Gson().fromJson(carBrandFragmentArgs.getBrand(),CarBrand.class);
            Glide.with(getContext())
                    .load(carBrand.getLogo())
                    .into(ivBrandLogo);
            tvBrandName.setText(carBrand.getName());
            carBrandViewModel.getCarSeries(carBrand.getId())
                    .observe(this,pageBaseResponse -> {
                        if(pageBaseResponse.isSuccess()){
                            drawerLayout.openDrawer(Gravity.RIGHT);
                            carSeriesAdapter=new CarSeriesAdapter(getContext(),pageBaseResponse.getData());
                            carSeriesAdapter.setOnClickListener(carSeriesOnClickListener);
                            rvCarSeries.setAdapter(carSeriesAdapter);
                        }
                    });
        }
        carBrandViewModel.getCarBrands()
                .observe(this,pageBaseResponse -> {
                    smartRefreshLayout.finishLoadmore();
                    smartRefreshLayout.finishRefresh();
                    if(pageBaseResponse.isSuccess()){

                            if (rvCarBrand.getItemDecorationCount() > 0) {
                                for (int i = 0; i < rvCarBrand.getItemDecorationCount(); i++) {
                                    rvCarBrand.removeItemDecoration(rvCarBrand.getItemDecorationAt(i));
                                }
                            }
                            carBrandAdapter=new CarBrandAdapter(getContext(),pageBaseResponse.getData());
                            carBrandAdapter.setOnClickListener(carBrandOnClickListener);
                            StickyRecyclerHeadersDecoration stickyRecyclerHeadersDecoration=new StickyRecyclerHeadersDecoration(carBrandAdapter);
                            rvCarBrand.addItemDecoration(stickyRecyclerHeadersDecoration);
                            rvCarBrand.setAdapter(carBrandAdapter);

                        }

                });
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public int layoutId() {
        return R.layout.fragment_car_brand;
    }

    @Override
    public boolean initView() {
        getDigger().inject(this);
        title.setText(getString(R.string.car_brand_title));
        smartRefreshLayout.setEnableRefresh(false);
        smartRefreshLayout.setEnableLoadmore(false);
        rvCarBrand.setLayoutManager(new LinearLayoutManager(getContext()));
        rvCarBrand.setIndexBarTransparentValue(0);
        rvCarBrand.setIndexBarTextColor(R.color.blue_0f6eff);
        rvCarBrand.setIndexBarStrokeVisibility(false);
        rvCarSeries.setLayoutManager(new LinearLayoutManager(getContext()));
        DrawerLayout.LayoutParams layoutParams= (DrawerLayout.LayoutParams) container.getLayoutParams();
        layoutParams.width= (int) (Tool.getScreenWidth(getContext())*0.7);
        container.setLayoutParams(layoutParams);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                getActivity(), drawerLayout, R.string.home_drawer_open, R.string.home_drawer_close) {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                if(drawerLayout==null){
                    return;
                }
                View mContent = drawerLayout.getChildAt(0);
                if(mContent!=null){

                    float scale = 1 - slideOffset;
                    drawerView.setAlpha(0.6f + 0.4f * (1 - scale));
                    //设置内容界面水平和垂直方向偏转量
                    //在滑动时内容界面的宽度为 屏幕宽度减去菜单界面所占宽度
                    DrawerLayout.LayoutParams layoutParams= (DrawerLayout.LayoutParams) container.getLayoutParams();
                    if(layoutParams.gravity==Gravity.LEFT){
                        mContent.setTranslationX(drawerView.getMeasuredWidth() * (1 - scale));
                    }else {
                        mContent.setTranslationX(-drawerView.getMeasuredWidth() * (1 - scale));
                    }
                    //设置内容界面操作无效（比如有button就会点击无效）
                    mContent.invalidate();
                }
            }
        };

        toggle.syncState();
        drawerLayout.addDrawerListener(toggle);
        onLoadRetry();
        return true;
    }


    @OnClick(R.id.iv_back)
    public void backClick() {
      if(drawerLayout.isDrawerVisible(Gravity.RIGHT)){
           drawerLayout.closeDrawer(Gravity.RIGHT);
      }else {
          NavHostFragment.findNavController(this).navigateUp();
      }
    }

    OnClickListener<CarBrand> carBrandOnClickListener = carBrand -> {
        carBrandViewModel.getSelectedCarSeries().setValue(null);
        Glide.with(getContext())
                .load(carBrand.getLogo())
                .into(ivBrandLogo);
        tvBrandName.setText(carBrand.getName());
        carBrandViewModel.getSelectedCarBrand().setValue(carBrand);
        carBrandViewModel.getCarSeries(carBrand.getId())
                .observe(this, new Observer<BaseResponse<List<CarSeries>>>() {
                    @Override
                    public void onChanged(BaseResponse<List<CarSeries>> listBaseResponse) {
                        if(listBaseResponse.isSuccess()){
                            drawerLayout.openDrawer(Gravity.RIGHT);
                            carSeriesAdapter=new CarSeriesAdapter(getContext(),listBaseResponse.getData());
                            carSeriesAdapter.setOnClickListener(carSeriesOnClickListener);
                            rvCarSeries.setAdapter(carSeriesAdapter);
                        }
                    }
                });
    };
    OnClickListener<CarSeries> carSeriesOnClickListener= carSeries -> {
        carBrandViewModel.getSelectedCarModel().setValue(null);
        carBrandViewModel.getSelectedCarSeries().setValue(carSeries);
        CarModelFragmentArgs.Builder builder=new CarModelFragmentArgs.Builder();
        builder.setSeriesId(String.valueOf(carSeries.getId()));
        go(null,R.id.action_carBrandFragment_to_carModelFragment,builder.build().toBundle());

    };
}
